package br.ufpe.cin.quickmall.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.InvalidParameterException;

import br.ufpe.cin.quickmall.exception.CommException;

import android.util.Log;

public class JsonUtils {

	//FIXME this could be on a XML
	private static final String URL_JSON_ALL_OFFERS = 
			"http://ec2-177-71-157-181.sa-east-1.compute.amazonaws.com:8080/" +
					"quickmall-0.1/rest";

	//FIXME this could be on a XML
	private static final String URL_JSON_OFFERS_FROM_STORE = "http://ec2-177-71-157-181.sa-east-1.compute.amazonaws.com:8080/" +
			"quickmall-0.1/rest/";


	public static final String getJsonTextAllStores() throws CommException {
		Log.d("JsonUtils", "inside getJsonTextAllStores");
		return getJsonText(URL_JSON_ALL_OFFERS);
	}

	public static final String getJsonTextOffersFromStore(int id) throws CommException {
		return getJsonText(URL_JSON_OFFERS_FROM_STORE + id);
	}
	
	private static final String getJsonText (String URL) throws CommException {
		Log.d("JsonUtils", "inside getJsonTextAllStores");
		if (URL == null)
			throw new InvalidParameterException();
		
		try {
			InputStream is = new URL(URL).openStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

			StringBuilder sb = new StringBuilder();
			int cp;
			while ((cp = rd.read()) != -1) {
				sb.append((char) cp);
			}

			String jsonText = sb.toString();
			Log.d("JsonUtils", "outside getJsonText(URL)");
			return jsonText;

		} catch (MalformedURLException e) {
			throw new CommException();
		} catch (IOException e) {
			throw new CommException();
		}
	}
	
}